import mongoose from 'mongoose'

// 使用测试数据库
process.env.MONGODB_URI = 'mongodb://localhost:27017/live-chat-test'
process.env.REDIS_HOST = 'localhost'
process.env.REDIS_PORT = '6379'
process.env.JWT_SECRET = 'test-secret'

// 在所有测试之前连接数据库
beforeAll(async () => {
  await mongoose.connect(process.env.MONGODB_URI)
})

// 在每个测试之后清理数据库
afterEach(async () => {
  const collections = await mongoose.connection.db.collections()
  for (const collection of collections) {
    await collection.deleteMany({})
  }
})

// 在所有测试之后断开连接
afterAll(async () => {
  await mongoose.disconnect()
})

// Mock Redis
jest.mock('ioredis', () => {
  const Redis = jest.requireActual('ioredis')
  return jest.fn().mockImplementation(() => {
    return {
      get: jest.fn(),
      set: jest.fn(),
      setex: jest.fn(),
      del: jest.fn(),
      incr: jest.fn(),
      expire: jest.fn(),
      pipeline: jest.fn(() => ({
        exec: jest.fn(),
      })),
    }
  })
})
